package com.huikeportal.controller;


import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.huikeportal.controller.common.Lang;
import com.huikeportal.controller.common.Log;
import com.huikeportal.controller.common.MessageManager;
import com.huikeportal.model.DataTransInfo;
import com.huikeportal.model.Language;
import com.huikeportal.model.MessageCommon;
import com.huikeportal.model.PosAllInfo;
import com.huikeportal.model.PosApplication;
import com.huikeportal.model.PosDataManagerInfo;
import com.huikeportal.model.SiteAllInfo;
import com.huikeportal.model.SiteDataManagerInfo;
import com.huikeportal.model.SiteType;
import com.huikeportal.model.UserInfo;
import com.huikeportal.model.WordBook;
import com.huikeportal.model.common.PageDataVo;
import com.huikeportal.model.common.SqlParameter;
import com.huikeportal.service.DataTransitionService;
import com.huikeportal.service.LoginService;
import com.huikeportal.service.PosService;
import com.huikeportal.service.SelectSiteService;

/**
 * POS数据管理
 * 
 * @author focus
 * 
 */
@Controller
@Scope("prototype")
public class PosController {
	
	@Autowired
	private HttpSession session;
	
	@Autowired
	private PosService posService;
	
	@Autowired
	private LoginService loginService;
	
	@Autowired
	private SelectSiteService selectSiteService;
	
	@Autowired
	private DataTransitionService dataTransitionService;
	
	@InitBinder("posDataManagerInfo")
	public void initBinder(WebDataBinder binder) {
		binder.setFieldDefaultPrefix("posDataManagerInfo.");
	}

	@InitBinder("pageDataVo")
	public void initBinderPage(WebDataBinder binder) {
		binder.setFieldDefaultPrefix("pageDataVo.");
	}

	@RequestMapping("/posManager")
	public String posManager(PosDataManagerInfo posDataManagerInfo,
			PageDataVo pageDataVo, ModelMap model) throws Exception {
		
		// 获取登录用户的信息，用来过滤该用户可以看到的POS数据
		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
		userInfo = loginService.getUserInfo(userInfo);
		posDataManagerInfo.setUserId(userInfo.getUserId());
		String menuHtml = loginService.getMenuHtml(userInfo, "posManager");
		
		// 按钮权限
		String sysLang = session.getAttribute("sysLang").toString();
		SqlParameter sql = new SqlParameter();
		sql.setSysLang(sysLang);
		sql.setString("posManager");
		Integer menuId = selectSiteService.getMenuId(sql);
		List<WordBook> menuList = loginService.getUserButtonList(sysLang, userInfo.getUserId(), menuId);
		String author = "";
		for(int i=0,len=menuList.size();i<len;i++){
			author+=menuList.get(i).getDicValue();
		}
		
		// 获取用户权限下的所有广场
		List<SiteAllInfo> squareList = getAllGcList(userInfo);
		
		String permitSitesStr = getAllPermitSitesStr(userInfo);
		posDataManagerInfo.setSiteArea(permitSitesStr);
		
		List<SiteType> siteTypes = posService.getSiteTypes("hkcloud_site_type");
		
		if(posDataManagerInfo.getSquare()==null || "-1".equals(posDataManagerInfo.getSquare()) ){
			Iterator<SiteType> it = siteTypes.iterator();
			while(it.hasNext()){
				if(!"300".equals(it.next().getSiteTypeId())){
					it.remove();
				}
			}
			posDataManagerInfo.setSiteType("300");
		}
		
		model.addAttribute("siteTypes",siteTypes);
		model.addAttribute("menuHtml", menuHtml);// 左侧菜单html
		model.addAttribute("author",author);
		model.addAttribute("squareList",squareList);
		
		
		Language lang = Lang.getInfo("zh_cn");
		model.addAttribute("lang", lang);
		model.addAttribute("datetime",posService.getDate());
		return "posSite";
	}
	
	@ResponseBody
	@RequestMapping("/ajaxPosSiteList")
	public Map ajaxPosSiteList(String beginTime, String square,String siteType,String siteName,String currentPage,String showData) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		PosDataManagerInfo posDataManagerInfo = new PosDataManagerInfo();
		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
		
		String permitSitesStr = getAllPermitSitesStr(userInfo);
		posDataManagerInfo.setSiteArea(permitSitesStr);
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		posDataManagerInfo.setBeginTime(sdf.parse(beginTime));
		posDataManagerInfo.setSquare(square);
		posDataManagerInfo.setSiteType(siteType);
		posDataManagerInfo.setSiteName(URLDecoder.decode(siteName, "UTF-8"));
		posDataManagerInfo.setShowData(showData);
		posDataManagerInfo.setSource(MessageManager.getMsg("selectSource"));
		
		if(!"-1".equals(square) && "300".equals(siteType)){
			posDataManagerInfo.setSiteKey(square);
			posDataManagerInfo.setSquare("-1");
		}
		
		// 获取用户信息
		userInfo = loginService.getUserInfo(userInfo);
		// 获取当前系统语言
		String sysLang = session.getAttribute("sysLang").toString();
		// 获取用户语言包
		Language language = Lang.getInfo(sysLang);
		// 查询当前页面id
		SqlParameter sql = new SqlParameter();
		sql.setSysLang(sysLang);
		sql.setString("posManager");
		Integer menuId = selectSiteService.getMenuId(sql);
		// 获取用户权限按钮信息
		List<WordBook> buttonList = loginService.getUserButtonList(sysLang,
				userInfo.getUserId(), menuId);
		// 按钮过滤
		language = filterLanguage(language, buttonList);
		PageDataVo pageDataVo = new PageDataVo();
		// 默认显示第一页
		if (currentPage == null || "".equals(currentPage)) {
			pageDataVo.setCurrentPage(1);
		} else {
			pageDataVo.setCurrentPage(Integer.parseInt(currentPage));
		}
		// 获取每页显示条数
		pageDataVo.setPageSize(Integer.parseInt(MessageManager
				.getMsg("pageSize")));
		// 设置开始显示条数
		pageDataVo.setStartRow((pageDataVo.getCurrentPage() - 1)
				* pageDataVo.getPageSize());
		// 设置参数
		pageDataVo.setSearchParameter(posDataManagerInfo);
		// 获取当前页用户信息
		pageDataVo = posService.getPosSiteList(pageDataVo);
		map.put("language", language);// 系统语言包
		map.put("siteList", pageDataVo.getPageResult());// 结果集
		map.put("currentPage", pageDataVo.getCurrentPage());// 当前页
		map.put("maxPage", pageDataVo.getMaxPage());// 最大页
		map.put("recentUserName", userInfo.getUserName());// 当前登录用户名
		map.put("isDelete", language.getDelete());// 是否有删除权限
		return map;
	}
	
	
	/**
	 * 按钮过滤
	 * 
	 * @param language
	 *            语言包
	 * @param buttonList
	 *            按钮权限
	 * @return
	 * @throws Exception
	 */
	private Language filterLanguage(Language language, List<WordBook> buttonList)
			throws Exception {
		boolean add = false;
		boolean modify = false;
		boolean delete = false;
		for (int i = 0; i < buttonList.size(); i++) {
			if ("2".equals(buttonList.get(i).getDicCode())) {
				add = true;
			}
			if ("3".equals(buttonList.get(i).getDicCode())) {
				modify = true;
			}
			if ("4".equals(buttonList.get(i).getDicCode())) {
				delete = true;
			}
		}
		if (!add) {
			language.setAdd("");
		}
		if (!modify) {
			language.setModify("");
		}
		if (!delete) {
			language.setDelete("");
		}
		return language;
	}
	
	private List<SiteAllInfo>  getOriPermissionList(UserInfo userInfo) throws Exception{
		// lowPermission < 300 的是广场以上的权限
		return posService.getSitesByUser(userInfo);
	}
	
	private int getHighPermission(List<SiteAllInfo> oriList) throws Exception{
		return posService.getLowPermission(oriList);
	}
	
	private List<SiteAllInfo> getAllGcList(UserInfo userInfo) throws Exception{
		List<SiteAllInfo> list;
		List<SiteAllInfo> oriList = getOriPermissionList(userInfo);
		list = getHighPermission(oriList) <= 300 ? posService.getAllGcList(oriList) : new ArrayList<SiteAllInfo>();
		return list;
	}
	
	@RequestMapping("/posDataDetail")
	public String posDataDetail(PosDataManagerInfo posDataManagerInfo,
			PageDataVo pageDataVo, ModelMap model) throws Exception {
		
		// 获取登录用户的信息，用来过滤该用户可以看到的POS数据
		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
		userInfo = loginService.getUserInfo(userInfo);
		posDataManagerInfo.setUserId(userInfo.getUserId());
		String menuHtml = loginService.getMenuHtml(userInfo, "posManager");
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		
		String sysLang = session.getAttribute("sysLang").toString();
		SqlParameter sql = new SqlParameter();
		sql.setSysLang(sysLang);
		sql.setString("posManager");
		Integer menuId = selectSiteService.getMenuId(sql);
		List<WordBook> menuList = loginService.getUserButtonList(sysLang, userInfo.getUserId(), menuId);
		String author = "";
		for(int i=0,len=menuList.size();i<len;i++){
			author+=menuList.get(i).getDicValue();
		}
		
		model.addAttribute("menuHtml", menuHtml);// 左侧菜单html
		model.addAttribute("pageDataVo", pageDataVo);// 用户列表分页信息
		
		Language lang = Lang.getInfo("zh_cn");
		model.addAttribute("lang", lang);
		model.addAttribute("author",author);
		model.addAttribute("datetime",posService.getDate());
		model.addAttribute("transactionTimeStr",sdf.format(posDataManagerInfo.getTransactionTime()));
		return "posManager";
	}
	
	
	@ResponseBody
	@RequestMapping("/ajaxPosDetailList")
	public Map ajaxPosDetailList(String transactionTime, String siteKey,String siteName,String currentPage) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		PosDataManagerInfo posDataManagerInfo = new PosDataManagerInfo();
		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
		
		String permitSitesStr = getAllPermitSitesStr(userInfo);
		posDataManagerInfo.setSiteArea(permitSitesStr);
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		
		posDataManagerInfo.setTransactionTime(sdf.parse(transactionTime));
		posDataManagerInfo.setSiteKey(siteKey);
		posDataManagerInfo.setSiteName(URLDecoder.decode(siteName, "UTF-8"));
		posDataManagerInfo.setSource(MessageManager.getMsg("selectSource"));
		
		// 获取用户信息
		userInfo = loginService.getUserInfo(userInfo);
		// 获取当前系统语言
		String sysLang = session.getAttribute("sysLang").toString();
		// 获取用户语言包
		Language language = Lang.getInfo(sysLang);
		// 查询当前页面id
		SqlParameter sql = new SqlParameter();
		sql.setSysLang(sysLang);
		sql.setString("posManager");
		Integer menuId = selectSiteService.getMenuId(sql);
		// 获取用户权限按钮信息
		List<WordBook> buttonList = loginService.getUserButtonList(sysLang,
				userInfo.getUserId(), menuId);
		// 按钮过滤
		language = filterLanguage(language, buttonList);
		PageDataVo pageDataVo = new PageDataVo();
		// 默认显示第一页
		if (currentPage == null || "".equals(currentPage)) {
			pageDataVo.setCurrentPage(1);
		} else {
			pageDataVo.setCurrentPage(Integer.parseInt(currentPage));
		}
		// 获取每页显示条数
		pageDataVo.setPageSize(Integer.parseInt(MessageManager
				.getMsg("pageSize")));
		// 设置开始显示条数
		pageDataVo.setStartRow((pageDataVo.getCurrentPage() - 1)
				* pageDataVo.getPageSize());
		// 设置参数
		pageDataVo.setSearchParameter(posDataManagerInfo);
		// 获取当前页用户信息
		pageDataVo = posService.getPosDetail(pageDataVo);
		map.put("language", language);// 系统语言包
		map.put("posList", pageDataVo.getPageResult());// 结果集
		map.put("currentPage", pageDataVo.getCurrentPage());// 当前页
		map.put("maxPage", pageDataVo.getMaxPage());// 最大页
		map.put("recentUserName", userInfo.getUserName());// 当前登录用户名
		return map;
	}
	
	
	// 获取该用户所拥有的所有的店铺权限
	private String getAllPermitSitesStr(UserInfo userInfo) throws Exception{
		String permitSitesStr = "";
		
		// lowPermission < 300 的是广场以上的权限
		List<SiteAllInfo> permitSiteList = posService.getSitesByUser(userInfo);
		List<SiteAllInfo> allSiteList = new ArrayList<SiteAllInfo>();
		int lowPermission = posService.getLowPermission(permitSiteList);
		if(lowPermission < 300){
			List<SiteAllInfo> allGcList = posService.getAllGcList(permitSiteList);
			allSiteList = posService.getAllSiteList(allGcList);
			allSiteList.addAll(allGcList);
		}else if(lowPermission > 500){
			allSiteList = permitSiteList;
		}else{
			allSiteList = posService.getAllSiteList(permitSiteList);
		}
		permitSitesStr = posService.getSitePermitAreaStr(allSiteList);
		return permitSitesStr;
	}
	
	/**
	 * 新增POS数据提交
	 * 
	 * @param posDataManagerInfo
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/addPosData")
	public Map addPosData(String siteKey,String transactionNumber,String salesAmount,String details,String posDate, ModelMap model)
			throws Exception {
		Map<String,Object> map = new HashMap<String,Object>();
		PosDataManagerInfo posDataManagerInfo = new PosDataManagerInfo();
		posDataManagerInfo.setSiteKey(siteKey);
		posDataManagerInfo.setTransactionNumber(Integer.parseInt(transactionNumber));
		posDataManagerInfo.setSalesAmount(Double.parseDouble(salesAmount));
		posDataManagerInfo.setDetails(details);
		posDataManagerInfo.setInputType("1");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		posDataManagerInfo.setTransactionTime(sdf.parse(posDate));
		Map returnMap = posService.addPosData(posDataManagerInfo);
		
		map.put("posDataId", returnMap.get("posDataId"));
		map.put("siteKey", siteKey);
		return map;
	}
	
	/**
	 * 新增POS数据提交
	 * 
	 * @param posDataManagerInfo
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/addPosDataDetail")
	public Map addPosDataDetail(String siteKey,String transactionNumber,String salesAmount,String details,String transactionTime, ModelMap model)
			throws Exception {
		Map<String,Object> map = new HashMap<String,Object>();
		PosDataManagerInfo posDataManagerInfo = new PosDataManagerInfo();
		posDataManagerInfo.setSiteKey(siteKey);
		posDataManagerInfo.setTransactionNumber(Integer.parseInt(transactionNumber));
		posDataManagerInfo.setSalesAmount(Double.parseDouble(salesAmount));
		posDataManagerInfo.setDetails(details);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		posDataManagerInfo.setTransactionTime(sdf.parse(transactionTime));
		Map returnMap = new HashMap();
		
		PosAllInfo dataInBaseInfo = posService.getDataBySiteKAndTransT(posDataManagerInfo);
		if(dataInBaseInfo!=null){
			dataInBaseInfo.setSitekey(posDataManagerInfo.getSiteKey());
			dataInBaseInfo.setTransactiontime(posDataManagerInfo.getTransactionTime());
			dataInBaseInfo.setTransactionnumber(posDataManagerInfo.getTransactionNumber());
			dataInBaseInfo.setSalesamount(posDataManagerInfo.getSalesAmount());
			dataInBaseInfo.setDetails(posDataManagerInfo.getDetails());
			posDataManagerInfo.setInputType("2");
			posService.updateDataOfImport(dataInBaseInfo);
		}else{
			posDataManagerInfo.setInputType("2");
			returnMap = posService.addPosDataOfImport(posDataManagerInfo);
		}

		
		map.put("posDataId", returnMap.get("posDataId"));
		return map;
	}
	
	
	/**
	 * 修改POS数据修改
	 * 
	 * @param posDataManagerInfo
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/editPosData")
	public Map editPosData(String id,String siteKey,String transactionNumber,String salesAmount,String details,String posDate, ModelMap model)
			throws Exception {
		
		PosDataManagerInfo posDataManagerInfo = new PosDataManagerInfo();
		posDataManagerInfo.setId(Long.parseLong(id));
		posDataManagerInfo.setSiteKey(siteKey);
		posDataManagerInfo.setTransactionNumber(Integer.parseInt(transactionNumber));
		posDataManagerInfo.setSalesAmount(Double.parseDouble(salesAmount));
		posDataManagerInfo.setDetails(details);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		posDataManagerInfo.setTransactionTime(sdf.parse(posDate));
		MessageCommon messageCommon = posService.updatePosData(posDataManagerInfo);
		return new HashMap();
	}
	
	/**
	 * 修改POS数据提交
	 * 
	 * @param posDataManagerInfo
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/editPosDataDetail")
	public Map editPosDataDetail(String id,String transactionNumber,String salesAmount,String details,String transactionTime, ModelMap model)
			throws Exception {
		
		PosDataManagerInfo posDataManagerInfo = new PosDataManagerInfo();
		posDataManagerInfo.setId(Long.parseLong(id));
		posDataManagerInfo.setTransactionNumber(Integer.parseInt(transactionNumber));
		posDataManagerInfo.setSalesAmount(Double.parseDouble(salesAmount));
		posDataManagerInfo.setDetails(details);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		posDataManagerInfo.setTransactionTime(sdf.parse(transactionTime));
		MessageCommon messageCommon = posService.updatePosDataDetail(posDataManagerInfo);

		return new HashMap();
	}
	
	/**
	 * 删除POS数据
	 * 
	 * @param posDataManagerInfo
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/deletePosData")
	public Map deletePosData(String siteKey,String transactionTime, ModelMap model)
			throws Exception {
		
		HashMap<String,String> map = new HashMap<String,String>();
		PosDataManagerInfo posDataManagerInfo = new PosDataManagerInfo();
		posDataManagerInfo.setSiteKey(siteKey);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		posDataManagerInfo.setTransactionTime(sdf.parse(transactionTime));
		MessageCommon messageCommon = posService.deletePosData(posDataManagerInfo);
		map.put("flag", String.valueOf(messageCommon.isFlag()));
		
		return map;
		
	}
	
	
	/**
	 * 删除POS数据(根据ID)
	 * 
	 * @param posDataManagerInfo
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/deletePosDataDetail")
	public String deletePosDataDetail(String id, ModelMap model)
			throws Exception {
		
		PosDataManagerInfo posDataManagerInfo = new PosDataManagerInfo();
		posDataManagerInfo.setId(Long.parseLong(id));
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		MessageCommon messageCommon = posService.deletePosDataDetail(posDataManagerInfo);

		
		// 获取登录用户的信息，用来过滤该用户可以看到的POS数据
		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
		userInfo = loginService.getUserInfo(userInfo);
		posDataManagerInfo.setUserId(userInfo.getUserId());
		String menuHtml = loginService.getMenuHtml(userInfo, "posManager");
		
		String permitSitesStr = getAllPermitSitesStr(userInfo);
		posDataManagerInfo.setSiteArea(permitSitesStr);
		
		List<SiteType> siteTypes = posService.getSiteTypes("hkcloud_site_type");
		
		
		if (!messageCommon.isFlag()) {
			return "error";
		}
		PageDataVo pageDataVo = new PageDataVo();
		
		// 如果是初始化，默认显示第一页
		if (pageDataVo.getCurrentPage() == 0) {
			pageDataVo.setCurrentPage(1);
		}
		// 获取每页显示条数
		pageDataVo.setPageSize(Integer.parseInt(MessageManager
				.getMsg("pageSize")));
		// 设置开始显示条数
		pageDataVo.setStartRow((pageDataVo.getCurrentPage() - 1)
				* pageDataVo.getPageSize());
		pageDataVo.setSearchParameter(posDataManagerInfo);
		// 获取当前页用户信息
		pageDataVo = posService.getPosSiteList(pageDataVo);
		model.addAttribute("siteTypes",siteTypes);
		model.addAttribute("menuHtml", menuHtml);// 左侧菜单html
		model.addAttribute("pageDataVo", pageDataVo);// 用户列表分页信息
		
		Language lang = Lang.getInfo("zh_cn");
		model.addAttribute("lang", lang);
		return "posSite";
	}
	
	/**
	 * 上传excel并解析
	 * 
	 * @param file
	 * @param req
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/uploadPosData")
	public String uploadPosData(
			@RequestParam(value = "file", required = false) MultipartFile file,PosDataManagerInfo posDataManagerInfo,ModelMap model,
			HttpServletRequest req) throws Exception {
		try {
			Log log = Log.getLogger();
			// 获取登录用户的信息，用来过滤该用户可以看到的POS数据
			UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
			userInfo = loginService.getUserInfo(userInfo);
			posDataManagerInfo.setUserId(userInfo.getUserId());
			String menuHtml = loginService.getMenuHtml(userInfo, "posManager");
			
			// 按钮权限
			String sysLang = session.getAttribute("sysLang").toString();
			SqlParameter sql = new SqlParameter();
			sql.setSysLang(sysLang);
			sql.setString("posManager");
			Integer menuId = selectSiteService.getMenuId(sql);
			List<WordBook> menuList = loginService.getUserButtonList(sysLang, userInfo.getUserId(), menuId);
			String author = "";
			for(int i=0,len=menuList.size();i<len;i++){
				author+=menuList.get(i).getDicValue();
			}
			
			// 获取用户权限下的所有广场
			List<SiteAllInfo> squareList = getAllGcList(userInfo);
			
			String permitSitesStr = getAllPermitSitesStr(userInfo);
			posDataManagerInfo.setSiteArea(permitSitesStr);
			
			List<SiteType> siteTypes = posService.getSiteTypes("hkcloud_site_type");
			
			if(posDataManagerInfo.getSquare()==null || "-1".equals(posDataManagerInfo.getSquare()) ){
				Iterator<SiteType> it = siteTypes.iterator();
				while(it.hasNext()){
					if(!"300".equals(it.next().getSiteTypeId())){
						it.remove();
					}
				}
				posDataManagerInfo.setSiteType("300");
			}
			
			model.addAttribute("siteTypes",siteTypes);
			model.addAttribute("menuHtml", menuHtml);// 左侧菜单html
			model.addAttribute("squareList",squareList);
			
			
			Language lang = Lang.getInfo("zh_cn");
			model.addAttribute("lang", lang);
			model.addAttribute("author",author);
			model.addAttribute("datetime",posService.getDate());
			
			
			String typeId = MessageManager.getMsg("interfaceTypeId");
			PosApplication tempInfo = new PosApplication();
			tempInfo.setTypeId(typeId);
			tempInfo.setUserId(userInfo.getUserId());
			List<PosApplication> columnList = posService.getTemplateColumns(tempInfo);
			String tableName = "";
			String firstLineAbled = "";
			if(!columnList.isEmpty()){
				tableName = columnList.get(0).getTableName();
				firstLineAbled = columnList.get(0).getFirstLineAbled();
			}
			
			
			// 上传文件
			String fileName = file.getOriginalFilename();
			log.logger.info("+++++++++++++++++++");
			log.logger.info("+++ fileName: "+fileName);
			log.logger.info("+++++++++++++++++++");
			if("".equals(fileName)){
				return "posSite";
			}
			String path = req.getSession().getServletContext().getRealPath(
					"upload");
			File targetFile = new File(path, fileName);
			if (!targetFile.exists()) {
				targetFile.mkdirs();
			}
			try {
				file.transferTo(targetFile);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			String filePath = path + File.separator + fileName;
			log.logger.info("+++++++++++++++++++");
			log.logger.info("+++ filePath1: "+filePath);
			log.logger.info("+++++++++++++++++++");
			
			// 07+版本excel上传
			if (filePath.indexOf(".xlsx") != -1) {
				InputStream is = new FileInputStream(filePath);
				XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);
				XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0);
				for (int rowNum = 0; rowNum < xssfSheet.getLastRowNum()+1; rowNum++) {
					if("false".equals(firstLineAbled) && rowNum==0){
						continue;
					}
					XSSFRow xssfRow = xssfSheet.getRow(rowNum);
					PosDataManagerInfo info = new PosDataManagerInfo();
					for(int j=0;j<columnList.size();j++){
						PosApplication temp = columnList.get(j);
						String columnName = temp.getColumnName();
						int order = temp.getColumnOrder();
						if("SiteKey".equalsIgnoreCase(columnName)){
							info.setSiteKey(xssfRow.getCell(order).getStringCellValue());
						}else if("TransactionTime".equalsIgnoreCase(columnName)){
							Date date = xssfRow.getCell(order).getDateCellValue();
							SimpleDateFormat sdf = new SimpleDateFormat();
							String dateStr = sdf.format(date);
							Date newDate = sdf.parse(dateStr);
							info.setTransactionTime(newDate);
						}else if("TransactionNumber".equalsIgnoreCase(columnName)){
							Double number = xssfRow.getCell(order).getNumericCellValue();
							info.setTransactionNumber(number.intValue());
						}else if("SalesAmount".equalsIgnoreCase(columnName)){
							Double amount = xssfRow.getCell(order).getNumericCellValue();
							info.setSalesAmount(amount.floatValue());
						}else if("Details".equalsIgnoreCase(columnName)){
							info.setDetails(xssfRow.getCell(order).toString());
						}
					}
					
					PosAllInfo dataInBaseInfo = posService.getDataBySiteKAndTransT(info);
					
					DataTransInfo searchInfo = new DataTransInfo();
					searchInfo.setType("1");
					searchInfo.setState("1");
					List<DataTransInfo> mappingList = dataTransitionService.getMappingData(searchInfo);
					Set<String> filterSet = new HashSet<String>();
					for(int j=0,len=mappingList.size();j<len;j++){
						filterSet.add(mappingList.get(j).getInnerid());
					}
					
					if(dataInBaseInfo!=null){
						if(filterSet.contains(info.getSiteKey())){
							dataInBaseInfo.setSitekey(info.getSiteKey());
							dataInBaseInfo.setTransactiontime(info.getTransactionTime());
							dataInBaseInfo.setTransactionnumber(info.getTransactionNumber());
							dataInBaseInfo.setSalesamount(info.getSalesAmount());
							dataInBaseInfo.setDetails(info.getDetails());
							posService.updateDataOfImport(dataInBaseInfo);
						}
					}else{
						if(filterSet.contains(info.getSiteKey())){
							info.setInputType("2");
							posService.addPosDataOfImport(info);
						}
					}
				}
			
			}
			// 03版本excel上传
			else if (filePath.indexOf(".xls") != -1) {
				InputStream is = new FileInputStream(filePath);
				HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
				HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(0);
				for (int rowNum = 0; rowNum < hssfSheet.getLastRowNum()+1; rowNum++) {
					if("false".equals(firstLineAbled) && rowNum==0){
						continue;
					}
					HSSFRow hssfRow = hssfSheet.getRow(rowNum);
					PosDataManagerInfo info = new PosDataManagerInfo();
					for(int j=0;j<columnList.size();j++){
						PosApplication temp = columnList.get(j);
						String columnName = temp.getColumnName();
						int order = temp.getColumnOrder();
						if("SiteKey".equalsIgnoreCase(columnName)){
							info.setSiteKey(hssfRow.getCell(order).getStringCellValue());
						}else if("TransactionTime".equalsIgnoreCase(columnName)){
							Calendar today = Calendar.getInstance();
							today.setTime(new Date());
							today.getTime();
							Calendar aWeekBefore = Calendar.getInstance();
							aWeekBefore.setTime(new Date());
							aWeekBefore.add(Calendar.DAY_OF_MONTH, -7);
							aWeekBefore.getTime();
							Date date = null;
							try{
								date = hssfRow.getCell(order).getDateCellValue();	
							}catch(Exception e){
								String dateStr = hssfRow.getCell(order).toString();
								SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
								date = sdf.parse(dateStr);
							}
							
							Calendar importDate = Calendar.getInstance();
							importDate.setTime(date);
							importDate.getTime();
							if(importDate.before(today) && importDate.after(aWeekBefore)){
								info.setTransactionTime(date);
							}else{
								model.addAttribute("message", "导入失败,请导入一周以内的数据");
								return "posSite";
							}
						}else if("TransactionNumber".equalsIgnoreCase(columnName)){
							Double number;
							try{
								number = hssfRow.getCell(order).getNumericCellValue();
							}catch(Exception e){
								String numberStr = hssfRow.getCell(order).toString();
								number = Double.parseDouble(numberStr);
							}
							if(number < 2147483647){
								info.setTransactionNumber(number.intValue());
							}else{
								model.addAttribute("message", "导入失败,导入的交易笔数过大");
								return "posSite";
							}
						}else if("SalesAmount".equalsIgnoreCase(columnName)){
							Double amount;
							try{
								amount = hssfRow.getCell(order).getNumericCellValue();
							}catch(Exception e){
								String amountStr = hssfRow.getCell(order).toString();
								amount = Double.parseDouble(amountStr);
							}
							info.setSalesAmount(amount);
						}else if("Details".equalsIgnoreCase(columnName)){
							info.setDetails(hssfRow.getCell(order).toString());
						}
					}
					
					PosAllInfo dataInBaseInfo = posService.getDataBySiteKAndTransT(info);
					
					DataTransInfo searchInfo = new DataTransInfo();
					searchInfo.setType("1");
					searchInfo.setState("1");
					List<DataTransInfo> mappingList = dataTransitionService.getMappingSnData(searchInfo);
					Set<String> filterSet = new HashSet<String>();
					for(int j=0,len=mappingList.size();j<len;j++){
						filterSet.add(mappingList.get(j).getInnerid());
					}
					
					if(dataInBaseInfo!=null){
						if(filterSet.contains(info.getSiteKey())){
							dataInBaseInfo.setSitekey(info.getSiteKey());
							dataInBaseInfo.setTransactiontime(info.getTransactionTime());
							dataInBaseInfo.setTransactionnumber(info.getTransactionNumber());
							dataInBaseInfo.setSalesamount(info.getSalesAmount());
							dataInBaseInfo.setDetails(info.getDetails());
							posService.updateDataOfImport(dataInBaseInfo);
						}
					}else{
						if(filterSet.contains(info.getSiteKey())){
							info.setInputType("2");
							posService.addPosDataOfImport(info);
						}
					}
				}
			} else {
				model.addAttribute("message", "版本不支持");
				return "posSite";
			}
			model.addAttribute("message", "导入POS数据完成");
			
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("message", "导入POS数据失败，请检查导入文件是否符合要求");
		}
		
		
		return "posSite";
	}

}
